// API基础URL配置
const API_BASE_URL = 'http://localhost:5003';

document.addEventListener('DOMContentLoaded', function() {
    // 获取元素
    const loginTab = document.getElementById('login-tab');
    const registerTab = document.getElementById('register-tab');
    const loginForm = document.getElementById('login-form');
    const registerForm = document.getElementById('register-form');
    const togglePasswords = document.querySelectorAll('.toggle-password');

    // 根据 URL hash 切换表单
    function switchFormByHash() {
        if (window.location.hash === '#register') {
            loginForm.classList.remove('active');
            registerForm.classList.add('active');
            loginTab.classList.remove('active');
            registerTab.classList.add('active');
        } else {
            loginForm.classList.add('active');
            registerForm.classList.remove('active');
            loginTab.classList.add('active');
            registerTab.classList.remove('active');
        }
    }

    // 页面加载时检查 URL
    switchFormByHash();

    // 监听 URL 变化
    window.addEventListener('hashchange', switchFormByHash);

    // 切换密码可见性
    togglePasswords.forEach(function(toggle) {
        toggle.addEventListener('click', function() {
            const passwordInput = this.previousElementSibling;
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                this.classList.remove('fa-eye-slash');
                this.classList.add('fa-eye');
            } else {
                passwordInput.type = 'password';
                this.classList.remove('fa-eye');
                this.classList.add('fa-eye-slash');
            }
        });
    });

    // 处理登录表单提交
    loginForm.addEventListener('submit', function(e) {
        e.preventDefault();

        const username = document.getElementById('login-username').value;
        const password = document.getElementById('login-password').value;

        // 表单验证
        if (!username || !password) {
            showMessage('请填写所有必填字段');
            return;
        }

        // API请求
        fetch(`${API_BASE_URL}/user/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username: username,
                password: password
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                // 登录成功，保存token和用户信息
                localStorage.setItem('token', data.data.token);
                localStorage.setItem('user', JSON.stringify(data.data.user));

                showMessage('登录成功，正在跳转...');
                // 跳转到 index.html
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 1500);
            } else {
                showMessage(data.message || '登录失败，请检查用户名和密码');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showMessage('网络错误，请稍后再试');
        });
    });

    // 处理注册表单提交
    registerForm.addEventListener('submit', function(e) {
        e.preventDefault();

        const username = document.getElementById('register-username').value;
        const email = document.getElementById('register-email').value;
        const password = document.getElementById('register-password').value;

        // 表单验证
        if (!username || !email || !password) {
            showMessage('请填写所有必填字段');
            return;
        }

        if (!isValidEmail(email)) {
            showMessage('请输入有效的电子邮箱地址');
            return;
        }

        if (password.length < 6) {
            showMessage('密码长度至少为6个字符');
            return;
        }

        // API请求
        fetch(`${API_BASE_URL}/user/register`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username: username,
                email: email,
                password: password
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                showMessage('注册成功，请登录');
                loginTab.click();
                document.getElementById('login-username').value = username;
            } else {
                showMessage(data.message || '注册失败，请稍后再试');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showMessage('网络错误，请稍后再试');
        });
    });

    // 辅助函数：显示消息
    function showMessage(message) {
        const messageContainer = document.createElement('div');
        messageContainer.className = 'message';
        messageContainer.textContent = message;
        messageContainer.style.position = 'fixed';
        messageContainer.style.top = '20px';
        messageContainer.style.left = '50%';
        messageContainer.style.transform = 'translateX(-50%)';
        messageContainer.style.padding = '10px 20px';
        messageContainer.style.backgroundColor = '#333';
        messageContainer.style.color = '#fff';
        messageContainer.style.borderRadius = '5px';
        messageContainer.style.zIndex = '1000';

        document.body.appendChild(messageContainer);

        setTimeout(() => {
            messageContainer.remove();
        }, 3000);
    }

    // 辅助函数：验证邮箱地址
    function isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }

    // 点击标签切换时更新 URL
    loginTab.addEventListener('click', function() {
        window.location.hash = 'login';
    });

    registerTab.addEventListener('click', function() {
        window.location.hash = 'register';
    });
});

// 获取用户信息的函数
async function fetchUserProfile() {
    try {
        const token = localStorage.getItem('token');
        if (!token) return null;

        const response = await fetch(`${API_BASE_URL}/user/profile`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });

        const data = await response.json();
        if (data.code === 200) {
            return data.data;
        } else {
            console.error('获取用户信息失败:', data.message);
            return null;
        }
    } catch (error) {
        console.error('获取用户信息出错:', error);
        return null;
    }
}

// 更新用户信息显示
document.addEventListener('DOMContentLoaded', async function() {
    const userInfoDiv = document.querySelector('.user-info');
    const authButtons = document.querySelector('.auth-buttons');
    const usernameDisplay = document.getElementById('username-display');

    // 获取最新的用户信息
    const userProfile = await fetchUserProfile();
    
    if (userProfile) {
        userInfoDiv.style.display = 'block';
        authButtons.style.display = 'none';
        usernameDisplay.textContent = userProfile.username;
    } else {
        userInfoDiv.style.display = 'none';
        authButtons.style.display = 'block';
    }

    // 用户详情模态窗口
    const userModal = document.getElementById("user-modal");
    const usernameSpan = document.getElementById("username-display");
    const closeButton = userModal.querySelector(".close-button");

    // 点击用户名显示模态窗口
    usernameSpan.onclick = async function() {
        // 重新获取最新的用户信息
        const userProfile = await fetchUserProfile();
        if (userProfile) {
            document.getElementById("modal-username").textContent = userProfile.username;
            document.getElementById("modal-email").textContent = userProfile.email;
            document.getElementById("modal-userid").textContent = userProfile.user_id;
            userModal.style.display = "block";
        } else {
            // 如果获取信息失败，可能是token过期
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            window.location.href = 'auth.html#login';
        }
    }

    // 点击关闭按钮关闭模态窗口
    closeButton.onclick = function() {
        userModal.style.display = "none";
    }

    // 点击模态窗口外部关闭
    window.onclick = function(event) {
        if (event.target == userModal) {
            userModal.style.display = "none";
        }
    }
});
